package com.example.demo.services;

import com.example.demo.models.RegionStats;
import com.sun.net.httpserver.Headers;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.function.ServerRequest;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;

@Service
public class CoronaVirusDataService implements InitializingBean{
    private  final String CORONA_VIRUS_DATE_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<RegionStats> allRegionStats = new ArrayList<>();

    public List<RegionStats> getAllRegionStats() {
        return allRegionStats;
    }

    @Scheduled(cron = "${sai.Schedules.updateVirusDataCron}")
    public  void fetchCoronaVirusData() throws Exception {

        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATE_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        StringReader in = new StringReader(StreamUtils.copyToString(Objects.requireNonNull(body).getInputStream(), Charset.defaultCharset()));
//        Reader in = new InputStreamReader(body.getInputStream(), "UTF-8");
//        Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
        List<String> datelist = new ArrayList<>();
        boolean isheader = true;
        for (CSVRecord record : records) {

            if(isheader) {
                isheader = false;
                for (int i = record.size() - 1; i >= 4; i--) {
                    String[] split = record.get(i).split("/");
                    datelist.add("20" + split[2] + "年" + split[0] + "月" + split[1] + "日");
                }
            }
            else {
                String state = record.get(0);
                String country = record.get(1);
                int newtotal = Integer.parseInt(record.get(record.size() - 1));
                int oldtotal = Integer.parseInt(record.get(record.size() - 2));
                int diffFromPrevDay = newtotal - oldtotal;
                Map<String, Long> map = new LinkedHashMap<>();
                for (int i = record.size() - 1, j = 0; i >= 4; i--, j++) {
                    map.put(datelist.get(j), Long.valueOf(record.get(i)));
                }
                RegionStats regionStats = new RegionStats(state, country, newtotal, diffFromPrevDay,map);
                allRegionStats.add(regionStats);
                System.out.println(state);
            }

        }

    }


    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();

    }
}
